import Vue from 'vue';
import App from './App.vue';
import router from './router';
import ElementUI from 'element-ui';
import VueI18n from 'vue-i18n';
import axios from 'axios';
import { Message } from 'element-ui';
// import service from "./utils/request"

import { messages } from './components/common/i18n';
import 'element-ui/lib/theme-chalk/index.css'; // 默认主题
// import './assets/css/theme-green/index.css'; // 浅绿色主题
import './assets/css/icon.css';
import './components/common/directives';
import 'babel-polyfill';
import store from "./store"


Vue.config.productionTip = false;
axios.defaults.timeout = 5000;//设置超时时间
axios.interceptors.request.use(
    config => {

        config.headers.Authorization = sessionStorage.getItem("token");//把localStorage的token放在Authorization里
        console.log(111);
        console.log(config.url);
        return config;
    },
    function(err) {
        console.log(err);
        return Promise.reject();
    }
);
axios.interceptors.response.use(
    response => {return response},
    error => {
        console.log(error.response.data.message);
        Message.error(error.response.data.message);
        return Promise.reject();

    }
);
Vue.prototype.$axios = axios;


Vue.use(VueI18n);
Vue.use(ElementUI, {
    size: 'small'
});
const i18n = new VueI18n({
    locale: 'zh',
    messages
});

//使用钩子函数对路由进行权限跳转
router.beforeEach((to, from, next) => {
    document.title = `${to.meta.title}`;

    let hasRoute = store.state.menus.hasRoutes;

    let token = sessionStorage.getItem("token")
    if (to.path === '/login') {
        next()

    } else if (!token) {
        next({path: '/login'})


    } else if(token && !hasRoute) {
        axios.get("/api/sysUser/perm", {
            headers: {
                Authorization: sessionStorage.getItem("token")
            }
        }).then(res => {

            console.log(res.data.data);

            // 拿到用户权限
            store.commit("setPermList", res.data.data);

            hasRoute = true;
            store.commit("changeRouteStatus", hasRoute);
        })
    }

    next()
});

new Vue({
    router,
    i18n,
    store:store,
    render: h => h(App)
}).$mount('#app');
